package com.bruce.practice.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.stream.IntStream;

/**
 * @author luotuan
 * @Description
 * @create 2020-05-19 11:02
 **/
public class SemaphoreTest {
    private static final int COUNT = 8;
    private static final Semaphore SEMAPHORE = new Semaphore(5);
    private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(10);

    public static void main(String[] args) {
        IntStream.range(0,COUNT).forEach((i)->{
            EXECUTOR_SERVICE.execute(new Worker(String.valueOf(i),SEMAPHORE));
        });
    }
}

class Worker implements Runnable {
    private String name;
    private Semaphore semaphore;

    public Worker(String name, Semaphore semaphore) {
        this.name = name;
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        try {
            semaphore.acquire();
            System.out.println("工人:【"+name+"】正在使用1个机器");
            Thread.sleep(500L);
            semaphore.release();
            System.out.println("工人:【"+name+"】释放了1个机器");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
